<template>
    <div class="professional-detail">

        <!-- 八字表格展示 -->
        <BaziTable 
            :bazi-data="baziPillars" 
            :decade="selectedDecadePillar"
            :fortune="selectedFortunePillar"
            :month-time="selectedMonthPillar"
            :day-time="selectedDayPillar"
            :hour-time="selectedHourPillar"
            :is-xiaoyun="isXiaoyun"
            :show-label-column="false"
        />
        <!-- 大运 -->
        <div class="level-row">
            <div class="level-label">
                <div>大运</div>
                <div class="switch-container" @click.stop="toggleFortuneDisplayMode">
                    <div class="switch" :class="{ 'switch-on': fortuneDisplayMode === 'expanded' }">
                        <div class="switch-handle"></div>
                    </div>
                </div>
            </div>
            <div 
                class="level-content" 
                ref="decadeScrollRef"
                @touchstart="(e) => handleTouchStart(e, 'decade')"
                @touchmove="(e) => handleTouchMove(e, 'decade')"
                @touchend="(e) => handleTouchEnd(e, 'decade')"
            >
                <div 
                    class="level-items"
                    :class="{ 'no-transition': decadeDragState.isDragging }"
                    :style="{ transform: `translateX(${decadeScrollX}px)` }"
                >
                    <div
                        v-for="(item, index) in decadeList"
                        :key="index"
                        class="row_item_wrapper level-item"
                        :class="{ active: selectedDecadeIndex === index }"
                        @click="selectDecade(index)"
                    >
                        <div class="row_scroll_item_text1">{{ item.startYear || '' }}</div>
                        <div class="row_scroll_item_text2">{{ item.xiaoyun ? (item.startAge && item.endAge ? `${item.startAge}-${item.endAge}岁` : (item.startAge ? `${item.startAge}岁` : '')) : (item.startAge ? `${item.startAge}岁` : '') }}</div>
                        <div class="row_scroll_item_text5" v-if="!item.xiaoyun">
                            <span>{{ extractStem(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.heavenStemShort || '' }}</span>
                        </div>
                        <div class="row_scroll_item_text5" v-if="!item.xiaoyun">
                            <span>{{ extractBranch(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.earthBranchShort || '' }}</span>
                        </div>
                        <div v-if="item.xiaoyun" class="xiaoyun-text">小运</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流年 -->
        <div v-if="fortuneList.length > 0 || fortuneDisplayMode === 'expanded'" class="level-row">
            <div class="level-label">
                <div v-if="fortuneDisplayMode === 'expanded'" class="level-label-text-start">始于</div>
                <div v-if="fortuneDisplayMode === 'expanded'" class="level-label-expanded">
                    <div>流年</div>
                </div>
                <div v-else class="level-label-normal">
                    <div>流年</div>
                    <div class="level-label-text-small">小运</div>
                </div>
                <div v-if="fortuneDisplayMode === 'expanded'" class="level-label-text-end">止于</div>
            </div>
            <div 
                class="level-content" 
                ref="fortuneScrollRef"
                @touchstart="(e) => handleTouchStart(e, 'fortune')"
                @touchmove="(e) => handleTouchMove(e, 'fortune')"
                @touchend="(e) => handleTouchEnd(e, 'fortune')"
            >
                <!-- 展开模式：显示大运对应的流年 -->
                <div 
                    v-if="fortuneDisplayMode === 'expanded'" 
                    class="row_scroll"
                    :class="{ 'no-transition': fortuneDragState.isDragging }"
                    :style="{ transform: `translateX(${fortuneScrollX}px)` }"
                >
                    <div
                        v-for="(decade, decadeIndex) in decadeList"
                        :key="decadeIndex"
                        class="row_item"
                        v-show="!decade.xiaoyun || getFortuneItemsForDecade(decadeIndex).length > 0"
                    >
                        <div class="row_item_wrapper row_item_wrapper-dy">
                            <!-- 开始年 -->
                            <div class="row_item_label">{{ decade.startYear || '' }}</div>
                            <!-- 流年干支列表 -->
                            <div class="row_item_value_wrapper">
                                <div
                                    v-for="(item, index) in getFortuneItemsForDecade(decadeIndex)"
                                    :key="index"
                                    class="row_item_value"
                                    :class="{ 'row_item_selected': selectedDecadeIndex === decadeIndex && selectedFortuneIndex === index }"
                                    @click="selectFortuneFromDecade(decadeIndex, index)"
                                >
                                    <span>{{ extractStem(item) }}{{ extractBranch(item) }}</span>
                                </div>
                            </div>
                            <!-- 结束年 -->
                            <div class="row_item_label row_item_label-end">{{ decade.endYear || '' }}</div>
                        </div>
                    </div>
                </div>
                <!-- 普通模式：横向滚动 -->
                <div 
                    v-else
                    class="level-items"
                    :class="{ 'no-transition': fortuneDragState.isDragging }"
                    :style="{ transform: `translateX(${fortuneScrollX}px)` }"
                >
                    <div
                        v-for="(item, index) in fortuneList"
                        :key="index"
                        class="row_item_wrapper level-item"
                        :class="{ active: selectedFortuneIndex === index }"
                        @click="selectFortune(index)"
                    >
                        <div class="row_scroll_item_text1">{{ item.year || '' }}</div>
                        <div class="row_scroll_item_text4"></div>
                        <div class="row_scroll_item_text5">
                            <span>{{ extractStem(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.heavenStemShort || '' }}</span>
                        </div>
                        <div class="row_scroll_item_text5">
                            <span>{{ extractBranch(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.earthBranchShort || '' }}</span>
                        </div>
                        <div class="row_scroll_item_text3">{{ item.childFortuneSixtyCycle || '' }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流月 -->
        <div v-if="monthList.length > 0" class="level-row">
            <div class="level-label">
                <div>流月</div>
            </div>
            <div 
                class="level-content" 
                ref="monthScrollRef"
                @touchstart="(e) => handleTouchStart(e, 'month')"
                @touchmove="(e) => handleTouchMove(e, 'month')"
                @touchend="(e) => handleTouchEnd(e, 'month')"
            >
                <div 
                    class="level-items"
                    :class="{ 'no-transition': monthDragState.isDragging }"
                    :style="{ transform: `translateX(${monthScrollX}px)` }"
                >
                    <div
                        v-for="(item, index) in monthList"
                        :key="index"
                        class="liu_row_li_item level-item"
                        :class="{ active: selectedMonthIndex === index }"
                        @click="selectMonth(index)"
                    >
                        <div class="dayun_nian">{{ item.startSolarTerm || '' }}</div>
                        <div class="dayun_age">{{ item.startDate ? `${item.startDate.month}/${item.startDate.day}` : '' }}</div>
                        <div>
                            <span>{{ extractStem(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.heavenStemShort || '' }}</span>
                        </div>
                        <div>
                            <span>{{ extractBranch(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.earthBranchShort || '' }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流日 -->
        <div v-if="dayList.length > 0" class="level-row">
            <div class="level-label">
                <div>流日</div>
            </div>
            <div 
                class="level-content" 
                ref="dayScrollRef"
                @touchstart="(e) => handleTouchStart(e, 'day')"
                @touchmove="(e) => handleTouchMove(e, 'day')"
                @touchend="(e) => handleTouchEnd(e, 'day')"
            >
                <div 
                    class="level-items"
                    :class="{ 'no-transition': dayDragState.isDragging }"
                    :style="{ transform: `translateX(${dayScrollX}px)` }"
                >
                    <div
                        v-for="(item, index) in dayList"
                        :key="index"
                        class="liu_row_li_item level-item"
                        :class="{ active: selectedDayIndex === index }"
                        @click="selectDay(index)"
                    >
                        <div class="dayun_nian">{{ item.date?.lunar?.dayName || '' }}</div>
                        <div class="dayun_age">{{ item.date?.solar ? `${item.date.solar.month}/${item.date.solar.day}` : '' }}</div>
                        <div>
                            <span>{{ extractStem(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.heavenStemShort || '' }}</span>
                        </div>
                        <div>
                            <span>{{ extractBranch(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.earthBranchShort || '' }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流时 -->
        <div v-if="hourList.length > 0" class="level-row">
            <div class="level-label">
                <div>流时</div>
            </div>
            <div 
                class="level-content" 
                ref="hourScrollRef"
                @touchstart="(e) => handleTouchStart(e, 'hour')"
                @touchmove="(e) => handleTouchMove(e, 'hour')"
                @touchend="(e) => handleTouchEnd(e, 'hour')"
            >
                <div 
                    class="level-items"
                    :class="{ 'no-transition': hourDragState.isDragging }"
                    :style="{ transform: `translateX(${hourScrollX}px)` }"
                >
                    <div
                        v-for="(item, index) in hourList"
                        :key="index"
                        class="liu_row_li_item level-item"
                        :class="{ active: selectedHourIndex === index }"
                        @click="selectHour(index)"
                    >
                        <div class="dayun_shi">{{ formatHourTime(item) }}</div>
                        <div class="dayun_age"></div>
                        <div>
                            <span>{{ extractStem(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.heavenStemShort || '' }}</span>
                        </div>
                        <div>
                            <span>{{ extractBranch(item) }}</span>
                            <span class="liuss">{{ item.tenStar?.earthBranchShort || '' }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 智能干支图示按钮 -->
        <div v-if="canShowRelationButton" class="relation-button-container">
            <van-button 
                type="primary" 
                block 
                round
                class="relation-button"
                @click="goToRelations"
            >
                智能干支图示
            </van-button>
        </div>
        
        <!-- 岁运关系 -->
        <SuiyunRelations
            :decade="selectedDecadePillar"
            :fortune="selectedFortunePillar"
            :month-time="selectedMonthPillar"
            :day-time="selectedDayPillar"
            :hour-time="selectedHourPillar"
            :show-tai-ming-shen="props.enableZiShiSupport"
            :taiyuan="props.baziData?.taiyuan"
            :minggong="props.baziData?.minggong"
            :shengong="props.baziData?.shengong"
            :bazi-data="props.baziData"
        />
        
        <!-- 分割线 -->
        <div class="divider"></div>
        
        <!-- 原局关系 -->
        <YuanjuRelations :bazi-data="props.baziData || null" />

        <!-- 分割线 -->
        <div class="divider"></div>
        
        <!-- 神煞显示 -->
        <ShenshaDisplay
            :bazi-data="props.baziData"
            :decade-list="decadeList"
            :fortune-list="fortuneList"
            :month-list="monthList"
            :day-list="dayList"
            :hour-list="hourList"
            :selected-decade-index="selectedDecadeIndex"
            :selected-fortune-index="selectedFortuneIndex"
            :selected-month-index="selectedMonthIndex"
            :selected-day-index="selectedDayIndex"
            :selected-hour-index="selectedHourIndex"
        />
      
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { baziApi } from '@/api/bazi'
import BaziTable from '@/components/bazi_table.vue'
import SuiyunRelations from '@/components/SuiyunRelations.vue'
import YuanjuRelations from '@/components/YuanjuRelations.vue'
import ShenshaDisplay from '@/components/ShenshaDisplay.vue'


interface Pillar {
    stem?: string
    branch?: string
    tenStar?: string
    zanggan?: any[]
    nayin?: string
    zizuo?: string
    kongwang?: string
    shenshas?: string[]
}

interface BaziData {
    year?: Pillar
    month?: Pillar
    day?: Pillar
    hour?: Pillar
    shengong?: Pillar
    minggong?: Pillar
    taiyuan?: Pillar
}

interface Props {
    datetime: string
    gender: number
    enableZiShiSupport?: boolean
    baziData?: BaziData // 四柱八字数据
}

const props = defineProps<Props>()

const router = useRouter()
const route = useRoute()

// 验证并转换gender为有效的数字类型（0或1）
const getValidGender = (): number => {
    const gender = Number(props.gender)
    // 确保gender是0或1，否则默认为1（男）
    return (gender === 0 || gender === 1) ? gender : 1
}

// 数据列表
const decadeList = ref<any[]>([])
const fortuneList = ref<any[]>([])
const monthList = ref<any[]>([])
const dayList = ref<any[]>([])
const hourList = ref<any[]>([])

// 选中的索引
const selectedDecadeIndex = ref<number>(-1)
const selectedFortuneIndex = ref<number>(-1)
const selectedMonthIndex = ref<number>(-1)
const selectedDayIndex = ref<number>(-1)
const selectedHourIndex = ref<number>(-1)

// 流年显示模式：'normal' 普通模式（横向滚动），'expanded' 展开模式（显示所有大运的流年）
const fortuneDisplayMode = ref<'normal' | 'expanded'>('normal')

// 滚动容器引用
const decadeScrollRef = ref<HTMLElement | null>(null)
const fortuneScrollRef = ref<HTMLElement | null>(null)
const monthScrollRef = ref<HTMLElement | null>(null)
const dayScrollRef = ref<HTMLElement | null>(null)
const hourScrollRef = ref<HTMLElement | null>(null)

// 滚动位置状态
const decadeScrollX = ref(0)
const fortuneScrollX = ref(0)
const monthScrollX = ref(0)
const dayScrollX = ref(0)
const hourScrollX = ref(0)

// 拖拽状态
interface DragState {
    isDragging: boolean
    isHorizontalDrag: boolean
    touchStartX: number
    touchStartY: number
    touchStartScrollX: number
}

const decadeDragState = ref<DragState>({
    isDragging: false,
    isHorizontalDrag: false,
    touchStartX: 0,
    touchStartY: 0,
    touchStartScrollX: 0
})

const fortuneDragState = ref<DragState>({
    isDragging: false,
    isHorizontalDrag: false,
    touchStartX: 0,
    touchStartY: 0,
    touchStartScrollX: 0
})

const monthDragState = ref<DragState>({
    isDragging: false,
    isHorizontalDrag: false,
    touchStartX: 0,
    touchStartY: 0,
    touchStartScrollX: 0
})

const dayDragState = ref<DragState>({
    isDragging: false,
    isHorizontalDrag: false,
    touchStartX: 0,
    touchStartY: 0,
    touchStartScrollX: 0
})

const hourDragState = ref<DragState>({
    isDragging: false,
    isHorizontalDrag: false,
    touchStartX: 0,
    touchStartY: 0,
    touchStartScrollX: 0
})

// 获取拖拽状态
const getDragState = (type: 'decade' | 'fortune' | 'month' | 'day' | 'hour'): DragState => {
    switch (type) {
        case 'decade': return decadeDragState.value
        case 'fortune': return fortuneDragState.value
        case 'month': return monthDragState.value
        case 'day': return dayDragState.value
        case 'hour': return hourDragState.value
    }
}

// 获取滚动位置
const getScrollX = (type: 'decade' | 'fortune' | 'month' | 'day' | 'hour'): number => {
    switch (type) {
        case 'decade': return decadeScrollX.value
        case 'fortune': return fortuneScrollX.value
        case 'month': return monthScrollX.value
        case 'day': return dayScrollX.value
        case 'hour': return hourScrollX.value
    }
}

// 设置滚动位置
const setScrollX = (type: 'decade' | 'fortune' | 'month' | 'day' | 'hour', value: number) => {
    switch (type) {
        case 'decade': 
            decadeScrollX.value = value
            // 展开模式下，大运滚动时同步流年滚动
            if (fortuneDisplayMode.value === 'expanded') {
                fortuneScrollX.value = value
            }
            break
        case 'fortune': 
            fortuneScrollX.value = value
            // 展开模式下，流年滚动时同步大运滚动
            if (fortuneDisplayMode.value === 'expanded') {
                decadeScrollX.value = value
            }
            break
        case 'month': monthScrollX.value = value; break
        case 'day': dayScrollX.value = value; break
        case 'hour': hourScrollX.value = value; break
    }
}

// 触摸开始
const handleTouchStart = (e: TouchEvent, type: 'decade' | 'fortune' | 'month' | 'day' | 'hour') => {
    e.stopPropagation()
    const touch = e.touches?.[0]
    if (!touch) return
    
    const dragState = getDragState(type)
    dragState.isDragging = true
    dragState.isHorizontalDrag = false
    dragState.touchStartX = touch.clientX
    dragState.touchStartY = touch.clientY
    dragState.touchStartScrollX = getScrollX(type)
    
    // 展开模式下，大运和流年同步拖拽状态
    if (fortuneDisplayMode.value === 'expanded') {
        if (type === 'decade') {
            const fortuneDragState = getDragState('fortune')
            fortuneDragState.isDragging = true
            fortuneDragState.isHorizontalDrag = false
            fortuneDragState.touchStartX = touch.clientX
            fortuneDragState.touchStartY = touch.clientY
            fortuneDragState.touchStartScrollX = getScrollX('fortune')
        } else if (type === 'fortune') {
            const decadeDragState = getDragState('decade')
            decadeDragState.isDragging = true
            decadeDragState.isHorizontalDrag = false
            decadeDragState.touchStartX = touch.clientX
            decadeDragState.touchStartY = touch.clientY
            decadeDragState.touchStartScrollX = getScrollX('decade')
        }
    }
}

// 触摸移动
const handleTouchMove = (e: TouchEvent, type: 'decade' | 'fortune' | 'month' | 'day' | 'hour') => {
    const dragState = getDragState(type)
    if (!dragState.isDragging) return
    
    const touch = e.touches?.[0]
    if (!touch) return
    
    const deltaX = Math.abs(touch.clientX - dragState.touchStartX)
    const deltaY = Math.abs(touch.clientY - dragState.touchStartY)
    
    // 判断滑动方向：如果水平滑动距离大于垂直滑动距离，则认为是水平滑动
    if (!dragState.isHorizontalDrag && deltaX > 10) {
        if (deltaX > deltaY) {
            dragState.isHorizontalDrag = true
        }
    }
    
    // 如果是水平滑动，处理水平滑动
    if (dragState.isHorizontalDrag) {
        e.stopPropagation()
        e.preventDefault()
        
        const newDeltaX = touch.clientX - dragState.touchStartX
        const newScrollX = dragState.touchStartScrollX + newDeltaX
        
        // 计算边界
        const container = e.currentTarget as HTMLElement
        // 展开模式下使用 .row_scroll，普通模式下使用 .level-items
        const wrapper = container.querySelector('.row_scroll') as HTMLElement || container.querySelector('.level-items') as HTMLElement
        if (container && wrapper) {
            const maxScroll = 0
            const wrapperWidth = wrapper.scrollWidth
            const containerWidth = container.offsetWidth
            const minScroll = containerWidth - wrapperWidth
            setScrollX(type, Math.max(minScroll, Math.min(maxScroll, newScrollX)))
        }
    }
    // 如果是垂直滑动，不阻止默认行为，让页面正常滚动
}

// 触摸结束
const handleTouchEnd = (e: TouchEvent, type: 'decade' | 'fortune' | 'month' | 'day' | 'hour') => {
    e.stopPropagation()
    const dragState = getDragState(type)
    dragState.isDragging = false
    dragState.isHorizontalDrag = false
    
    // 展开模式下，大运和流年同步拖拽状态
    if (fortuneDisplayMode.value === 'expanded') {
        if (type === 'decade') {
            const fortuneDragState = getDragState('fortune')
            fortuneDragState.isDragging = false
            fortuneDragState.isHorizontalDrag = false
        } else if (type === 'fortune') {
            const decadeDragState = getDragState('decade')
            decadeDragState.isDragging = false
            decadeDragState.isHorizontalDrag = false
        }
    }
}

// 从干支中提取天干
const extractStem = (item: any): string => {
    if (item.stem) {
        return item.stem
    }
    if (item.ganzhi && item.ganzhi.length >= 1) {
        return item.ganzhi[0]
    }
    return ''
}

// 从干支中提取地支
const extractBranch = (item: any): string => {
    if (item.branch) {
        return item.branch
    }
    if (item.ganzhi && item.ganzhi.length >= 2) {
        return item.ganzhi[1]
    }
    return ''
}


// 格式化流时时间
const formatHourTime = (item: any): string => {
    if (item.timeRange) {
        const start = String(item.timeRange.start).padStart(2, '0')
        return `${start}:00`
    }
    return ''
}

// 获取当前时间对应的索引
const getCurrentTimeIndex = (list: any[], timeField: string): number => {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    const currentDay = now.getDate()
    const currentHour = now.getHours()
    
    for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (timeField === 'year' && item.year === currentYear) {
            return i
        }
        if (timeField === 'month' && item.month === currentMonth) {
            return i
        }
        if (timeField === 'day' && item.day === currentDay) {
            return i
        }
        if (timeField === 'hour' && item.hour === currentHour) {
            return i
        }
    }
    return 0
}

// 滚动到选中项
const scrollToActive = (scrollRef: HTMLElement | null, index: number, type: 'decade' | 'fortune' | 'month' | 'day' | 'hour') => {
    if (!scrollRef) return
    // 展开模式下使用 .row_item，普通模式下使用 .level-item
    const items = scrollRef.querySelectorAll('.row_item, .level-item')
    if (items[index]) {
        const item = items[index] as HTMLElement
        const container = scrollRef
        const containerWidth = container.offsetWidth
        // 展开模式下使用 .row_scroll，普通模式下使用 .level-items
        const wrapper = container.querySelector('.row_scroll') as HTMLElement || container.querySelector('.level-items') as HTMLElement
        if (wrapper) {
            // 获取当前滚动位置
            const currentScrollX = getScrollX(type)
            // item.offsetLeft 是相对于 wrapper 的位置
            const itemLeft = item.offsetLeft
            const itemWidth = item.offsetWidth
            // 计算 item 在当前视口中的位置
            // currentScrollX 是负值（向左滚动），所以 itemLeftInView = itemLeft + currentScrollX
            const itemLeftInView = itemLeft + currentScrollX
            const itemRightInView = itemLeftInView + itemWidth
            const itemCenterInView = itemLeftInView + itemWidth / 2
            
            // 检查 item 是否已经在视口中可见（留出一些边距）
            const margin = 30
            const isFullyVisible = itemLeftInView >= margin && itemRightInView <= containerWidth - margin
            
            // 如果 item 不在视口中，或者不在中心位置，才进行滚动
            if (!isFullyVisible || Math.abs(itemCenterInView - containerWidth / 2) > 10) {
                const itemCenter = itemLeft + itemWidth / 2
                const containerCenter = containerWidth / 2
                // 计算目标滚动位置：使 item 的中心对齐到容器的中心
                const targetScrollX = containerCenter - itemCenter
                
                const maxScroll = 0
                const wrapperWidth = wrapper.scrollWidth
                const minScroll = containerWidth - wrapperWidth
                // 确保滚动位置在有效范围内
                const finalScrollX = Math.max(minScroll, Math.min(maxScroll, targetScrollX))
                setScrollX(type, finalScrollX)
            }
        }
    }
}

// 加载大运列表
const loadDecadeList = async () => {
    try {
        const response = await baziApi.getDecadeList({
            datetime: props.datetime,
            gender: getValidGender(),
            enableZiShiSupport: props.enableZiShiSupport
        })
        decadeList.value = (response.data?.data || response.data || []) as any[]
        
        // 默认选中第一个
        if (decadeList.value.length > 0) {
            selectedDecadeIndex.value = 0
            scrollToActive(decadeScrollRef.value, 0, 'decade')
            // 从大运的 children 中加载流年列表
            loadFortuneList(0)
        }
    } catch (error) {
        console.error('加载大运列表失败:', error)
    }
}

// 加载流年列表（从大运的 children 中获取）
const loadFortuneList = (decadeIndex: number) => {
    const selectedDecade = decadeList.value[decadeIndex]
    if (selectedDecade && selectedDecade.children) {
        fortuneList.value = selectedDecade.children as any[]
        
        // 默认选中当前年份
        if (fortuneList.value.length > 0) {
            const currentIndex = getCurrentTimeIndex(fortuneList.value, 'year')
            selectedFortuneIndex.value = currentIndex
            scrollToActive(fortuneScrollRef.value, currentIndex, 'fortune')
            // 加载流月列表
            if (currentIndex >= 0) {
                loadMonthList(decadeIndex, currentIndex)
            }
        } else {
            selectedFortuneIndex.value = -1
        }
    } else {
        fortuneList.value = []
        selectedFortuneIndex.value = -1
    }
}

// 加载流月列表
const loadMonthList = async (decadeIndex: number, fortuneIndex: number) => {
    try {
        const response = await baziApi.getMonthList({
            datetime: props.datetime,
            gender: getValidGender(),
            decadeIndex,
            fortuneIndex,
            enableZiShiSupport: props.enableZiShiSupport
        })
        monthList.value = (response.data?.data || response.data || []) as any[]
        
        // 流月默认不选中
        selectedMonthIndex.value = -1
    } catch (error) {
        console.error('加载流月列表失败:', error)
        monthList.value = []
    }
}

// 加载流日列表
const loadDayList = async (decadeIndex: number, fortuneIndex: number, monthIndex: number) => {
    try {
        const response = await baziApi.getDayList({
            datetime: props.datetime,
            gender: getValidGender(),
            decadeIndex,
            fortuneIndex,
            monthIndex,
            enableZiShiSupport: props.enableZiShiSupport
        })
        dayList.value = (response.data?.data || response.data || []) as any[]
        
        // 流日默认不选中，等待用户点击
        selectedDayIndex.value = -1
    } catch (error) {
        console.error('加载流日列表失败:', error)
        dayList.value = []
    }
}

// 加载流时列表
const loadHourList = async (decadeIndex: number, fortuneIndex: number, monthIndex: number, dayIndex: number) => {
    try {
        const response = await baziApi.getHourList({
            datetime: props.datetime,
            gender: getValidGender(),
            decadeIndex,
            fortuneIndex,
            monthIndex,
            dayIndex,
            enableZiShiSupport: props.enableZiShiSupport
        })
        hourList.value = (response.data?.data || response.data || []) as any[]
        
        // 流时默认不选中，等待用户点击
        selectedHourIndex.value = -1
    } catch (error) {
        console.error('加载流时列表失败:', error)
        hourList.value = []
    }
}

// 选择大运
const selectDecade = (index: number) => {
    if (decadeDragState.value.isDragging) return
    selectedDecadeIndex.value = index
    // 延迟执行滚动，确保 DOM 更新完成
    nextTick(() => {
        scrollToActive(decadeScrollRef.value, index, 'decade')
    })
    // 清空下级选择
    monthList.value = []
    dayList.value = []
    hourList.value = []
    selectedMonthIndex.value = -1
    selectedDayIndex.value = -1
    selectedHourIndex.value = -1
    // 从大运的 children 中加载流年列表
    loadFortuneList(index)
}

// 切换流年显示模式
const toggleFortuneDisplayMode = () => {
    fortuneDisplayMode.value = fortuneDisplayMode.value === 'normal' ? 'expanded' : 'normal'
    
    // 切换到普通模式时，根据当前选中的大运重新加载流年列表
    if (fortuneDisplayMode.value === 'normal' && selectedDecadeIndex.value >= 0) {
        loadFortuneList(selectedDecadeIndex.value)
    }
}

// 获取指定大运的流年列表
const getFortuneItemsForDecade = (decadeIndex: number) => {
    const decade = decadeList.value[decadeIndex]
    if (decade && decade.children) {
        return decade.children as any[]
    }
    return []
}

// 从展开模式选择流年
const selectFortuneFromDecade = (decadeIndex: number, fortuneIndex: number) => {
    selectedDecadeIndex.value = decadeIndex
    selectedFortuneIndex.value = fortuneIndex
    // 清空下级选择
    monthList.value = []
    dayList.value = []
    hourList.value = []
    selectedMonthIndex.value = -1
    selectedDayIndex.value = -1
    selectedHourIndex.value = -1
    // 加载流月列表
    loadMonthList(decadeIndex, fortuneIndex)
}

// 选择流年
const selectFortune = (index: number) => {
    if (fortuneDragState.value.isDragging) return
    selectedFortuneIndex.value = index
    scrollToActive(fortuneScrollRef.value, index, 'fortune')
    // 清空下级选择
    monthList.value = []
    dayList.value = []
    hourList.value = []
    selectedMonthIndex.value = -1
    selectedDayIndex.value = -1
    selectedHourIndex.value = -1
    // 加载流月列表
    loadMonthList(selectedDecadeIndex.value, index)
}

// 选择流月
const selectMonth = (index: number) => {
    if (monthDragState.value.isDragging) return
    selectedMonthIndex.value = index
    scrollToActive(monthScrollRef.value, index, 'month')
    // 清空下级选择
    dayList.value = []
    hourList.value = []
    selectedDayIndex.value = -1
    selectedHourIndex.value = -1
    // 加载流日列表
    loadDayList(selectedDecadeIndex.value, selectedFortuneIndex.value, index)
}

// 选择流日
const selectDay = (index: number) => {
    if (dayDragState.value.isDragging) return
    selectedDayIndex.value = index
    scrollToActive(dayScrollRef.value, index, 'day')
    // 清空下级选择
    hourList.value = []
    selectedHourIndex.value = -1
    // 加载流时列表
    loadHourList(selectedDecadeIndex.value, selectedFortuneIndex.value, selectedMonthIndex.value, index)
}

// 选择流时
const selectHour = (index: number) => {
    if (hourDragState.value.isDragging) return
    selectedHourIndex.value = index
    scrollToActive(hourScrollRef.value, index, 'hour')
}

// 计算选中的时间数据（用于传递给 BaziTable）
const selectedDecadePillar = computed(() => {
    if (selectedDecadeIndex.value >= 0 && decadeList.value[selectedDecadeIndex.value]) {
        const item = decadeList.value[selectedDecadeIndex.value]
        // 从大运数据中提取柱信息，使用完整十神名称
        return {
            stem: extractStem(item),
            branch: extractBranch(item),
            tenStar: item.tenStar?.heavenStem || item.tenStar?.heavenStemShort || '',
            zanggan: item.zanggan || [],
            nayin: item.nayin || '',
            zizuo: item.zizuo || '',
            xingyun: item.xingyun || '',
            kongwang: item.kongwang || '',
            shenshas: item.shenshas || []
        }
    }
    return undefined
})

const selectedFortunePillar = computed(() => {
    if (selectedFortuneIndex.value >= 0 && fortuneList.value[selectedFortuneIndex.value]) {
        const item = fortuneList.value[selectedFortuneIndex.value]
        return {
            stem: extractStem(item),
            branch: extractBranch(item),
            tenStar: item.tenStar?.heavenStem || item.tenStar?.heavenStemShort || '',
            zanggan: item.zanggan || [],
            nayin: item.nayin || '',
            zizuo: item.zizuo || '',
            xingyun: item.xingyun || '',
            kongwang: item.kongwang || '',
            shenshas: item.shenshas || []
        }
    }
    return undefined
})

const selectedMonthPillar = computed(() => {
    if (selectedMonthIndex.value >= 0 && monthList.value[selectedMonthIndex.value]) {
        const item = monthList.value[selectedMonthIndex.value]
        return {
            stem: extractStem(item),
            branch: extractBranch(item),
            tenStar: item.tenStar?.heavenStem || item.tenStar?.heavenStemShort || '',
            zanggan: item.zanggan || [],
            nayin: item.nayin || '',
            zizuo: item.zizuo || '',
            xingyun: item.xingyun || '',
            kongwang: item.kongwang || '',
            shenshas: item.shenshas || []
        }
    }
    return undefined
})

const selectedDayPillar = computed(() => {
    if (selectedDayIndex.value >= 0 && dayList.value[selectedDayIndex.value]) {
        const item = dayList.value[selectedDayIndex.value]
        return {
            stem: extractStem(item),
            branch: extractBranch(item),
            tenStar: item.tenStar?.heavenStem || item.tenStar?.heavenStemShort || '',
            zanggan: item.zanggan || [],
            nayin: item.nayin || '',
            zizuo: item.zizuo || '',
            xingyun: item.xingyun || '',
            kongwang: item.kongwang || '',
            shenshas: item.shenshas || []
        }
    }
    return undefined
})

const selectedHourPillar = computed(() => {
    if (selectedHourIndex.value >= 0 && hourList.value[selectedHourIndex.value]) {
        const item = hourList.value[selectedHourIndex.value]
        return {
            stem: extractStem(item),
            branch: extractBranch(item),
            tenStar: item.tenStar?.heavenStem || item.tenStar?.heavenStemShort || '',
            zanggan: item.zanggan || [],
            nayin: item.nayin || '',
            zizuo: item.zizuo || '',
            xingyun: item.xingyun || '',
            kongwang: item.kongwang || '',
            shenshas: item.shenshas || []
        }
    }
    return undefined
})

// 计算四柱数据（用于传递给 BaziTable）
const baziPillars = computed(() => {
    return props.baziData || {}
})

// 判断是否是小运（第一个大运且 xiaoyun: true）
const isXiaoyun = computed(() => {
    if (selectedDecadeIndex.value === 0 && decadeList.value.length > 0) {
        const firstDecade = decadeList.value[0]
        return firstDecade?.xiaoyun === true
    }
    return false
})

// 监听props变化
watch(() => [props.datetime, props.gender, props.enableZiShiSupport], () => {
    // 重置所有数据
    decadeList.value = []
    fortuneList.value = []
    monthList.value = []
    dayList.value = []
    hourList.value = []
    selectedDecadeIndex.value = -1
    selectedFortuneIndex.value = -1
    selectedMonthIndex.value = -1
    selectedDayIndex.value = -1
    selectedHourIndex.value = -1
    // 重置滚动位置
    decadeScrollX.value = 0
    fortuneScrollX.value = 0
    monthScrollX.value = 0
    dayScrollX.value = 0
    hourScrollX.value = 0
    // 重新加载
    loadDecadeList()
}, { immediate: false })

// 判断是否可以显示关系按钮（至少要有四柱数据）
const canShowRelationButton = computed(() => {
    return !!(props.baziData?.year && props.baziData?.month && props.baziData?.day && props.baziData?.hour)
})

// 跳转到智能干支图示页面
const goToRelations = () => {
    // 从当前路由参数获取参数，并添加选中的时间索引
    const params: any = {
        ...route.query,
        // 传递选中的时间索引（如果已选中）
        decadeIndex: selectedDecadeIndex.value >= 0 ? selectedDecadeIndex.value : undefined,
        fortuneIndex: selectedFortuneIndex.value >= 0 ? selectedFortuneIndex.value : undefined,
        monthIndex: selectedMonthIndex.value >= 0 ? selectedMonthIndex.value : undefined,
        dayIndex: selectedDayIndex.value >= 0 ? selectedDayIndex.value : undefined,
        hourIndex: selectedHourIndex.value >= 0 ? selectedHourIndex.value : undefined,
        // 标记来自专业细盘
        fromDetail: 'true'
    }
    
    // 移除 undefined 值
    Object.keys(params).forEach(key => {
        if (params[key] === undefined) {
            delete params[key]
        }
    })
    
    router.push({
        path: '/bazi/relations',
        query: params
    })
}

// 初始化
onMounted(() => {
    loadDecadeList()
})
</script>

<style scoped>
.professional-detail {
    width: 100%;
    max-width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 4px;
    position: relative;
    isolation: isolate; /* 创建新的层叠上下文，防止样式穿透 */
}

.level-row {
    display: flex;
    align-items: stretch;
    margin-bottom: 4px;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    position: relative;
    flex-wrap: nowrap; /* 防止换行 */
}

.level-row:last-child {
    margin-bottom: 0;
}

.level-label {
    font-size: 16px;
    color: #64748b;
    font-weight: 700;
    min-width: 35px;
    max-width: 50px;
    flex-shrink: 0;
    flex-grow: 0;
    padding: 0;
    box-sizing: border-box;
    position: relative;
    z-index: 10;
    background: transparent;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    align-self: stretch;
}

.level-label-expanded {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
}

.level-label-expanded > div {
    writing-mode: vertical-rl;
    text-orientation: upright;
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 6px;
    flex-shrink: 0;
}

.level-label-normal {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    width: 100%;
    min-width: 0;
    max-width: 100%;
    box-sizing: border-box;
    position: relative;
}

.level-label-normal > div:first-child {
    writing-mode: vertical-rl;
    text-orientation: upright;
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 6px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: auto 0;
}

.level-label-text-small {
    font-size: 12px;
    font-weight: 500;
    color: #64748b;
    letter-spacing: 1px;
    flex-shrink: 0;
    text-align: center;
    width: 100%;
    min-width: 0;
    max-width: 100%;
    box-sizing: border-box;
    writing-mode: horizontal-tb !important;
    text-orientation: mixed !important;
    white-space: nowrap;
    display: block;
    position: absolute;
    bottom: 7px;
    left: 0;
    right: 0;
}

.level-label > div:first-child:not(.level-label-text-start) {
    writing-mode: vertical-rl;
    text-orientation: upright;
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.level-label-text-start {
    font-size: 12px;
    font-weight: 500;
    color: #64748b;
    letter-spacing: 1px;
    flex-shrink: 0;
    text-align: center;
    width: 100%;
    writing-mode: horizontal-tb !important;
    text-orientation: mixed !important;
    white-space: nowrap;
    display: block;
}

.level-label-text-end {
    font-size: 12px;
    font-weight: 500;
    color: #64748b;
    letter-spacing: 1px;
    flex-shrink: 0;
    text-align: center;
    width: 100%;
    margin-top: auto;
    writing-mode: horizontal-tb;
    text-orientation: mixed;
    white-space: nowrap;
}

.switch-container {
    cursor: pointer;
    user-select: none;
}

.switch {
    width: 24px;
    height: 14px;
    background-color: #cbd5e1;
    border-radius: 7px;
    position: relative;
    transition: background-color 0.3s;
}

.switch.switch-on {
    background-color: #3b82f6;
}

.switch-handle {
    width: 10px;
    height: 10px;
    background-color: #fff;
    border-radius: 50%;
    position: absolute;
    top: 2px;
    left: 2px;
    transition: transform 0.3s;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.switch.switch-on .switch-handle {
    transform: translateX(10px);
}

.level-content {
    flex: 1;
    min-width: 0;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
    position: relative;
    -webkit-overflow-scrolling: touch;
    touch-action: pan-y pan-x;
}

.level-content:has(.fortune-expanded-container) {
    overflow-y: auto;
    overflow-x: hidden;
}

.level-items {
    display: flex;
    gap: 0;
    padding: 0;
    box-sizing: border-box;
    width: max-content; /* 允许内容超出容器宽度 */
    min-width: 100%;
    transition: transform 0.3s ease-out;
    will-change: transform;
}

.level-items.no-transition {
    transition: none;
}

.level-item {
    flex-shrink: 0;
    flex-grow: 0;
    width: 43px;
    padding: 6px 4px;
    margin: 4px 0;
    background: transparent;
    border-right: 0.5px solid #e2e8f0;
    cursor: pointer;
    transition: all 0.2s;
    text-align: center;
    box-sizing: border-box;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
}

.level-item:last-child {
    border-right: none;
}

.level-item:hover {
    background: #f1f5f9;
}

.level-item.active {
    background-color: #eee;
    color: #1e293b;
    font-weight: 700;
}

.item-header {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
}

.level-item.active .item-header {
    color: #fff;
}

.item-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
}

.item-line {
    line-height: 1.2;
    white-space: nowrap;
}

.level-item.active .item-content {
    color: #fff;
}

.level-item.active .item-line {
    color: #fff;
}

/* 参考结构样式 */
.row_item_wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}

.row_scroll_item_text1 {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.row_scroll_item_text2 {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.row_scroll_item_text3 {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.row_scroll_item_text4 {
    min-height: 0;
}

.row_scroll_item_text5 {
    font-size: 13px;
    font-weight: 400;
    color: #1e293b;
    line-height: 1.2;
}

.row_scroll_item_text5 span {
    font-size: 14px;
}

.row_scroll_item_text5 .liuss {
    font-size: 14px;
}

.liu_row_li_item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 3px;
}

.liu_row_li_item > div {
    font-size: 13px;
}

.liu_row_li_item > div span {
    font-size: 14px;
}

.liu_row_li_item > div .liuss {
    font-size: 14px;
}

.dayun_nian {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.dayun_age {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.dayun_shi {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
}

.liuss {
    color: #dc2626;
}

.level-item.active .row_scroll_item_text1,
.level-item.active .row_scroll_item_text2,
.level-item.active .row_scroll_item_text3,
.level-item.active .dayun_nian,
.level-item.active .dayun_age,
.level-item.active .dayun_shi {
    color: #1e293b;
    font-weight: 700;
}

.level-item.active .row_scroll_item_text5,
.level-item.active .liu_row_li_item > div {
    color: #1e293b;
    font-weight: 700;
}

.level-item.active .liuss {
    color: #dc2626;
    font-weight: 700;
}

.xiaoyun-text {
    writing-mode: vertical-rl;
    text-orientation: upright;
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    letter-spacing: 3px;
}

.level-item.active .xiaoyun-text {
    color: #1e293b;
    font-weight: 700;
}

/* 展开模式样式 */
.row_scroll {
    display: flex;
    gap: 0;
    padding: 0;
    box-sizing: border-box;
    width: max-content;
    min-width: 100%;
    transition: transform 0.3s ease-out;
    will-change: transform;
}

.row_scroll.no-transition {
    transition: none;
}

.row_item {
    flex-shrink: 0;
    flex-grow: 0;
    width: 43px;
    padding: 0 4px;
    border-right: 0.5px solid #e2e8f0;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    text-align: center;
}

.row_item:last-child {
    border-right: none;
}

.row_item_wrapper-dy {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    gap: 4px;
    width: 100%;
    min-width: 0;
    height: 100%;
}

.row_item_label {
    font-size: 12px;
    color: #1e293b;
    line-height: 1.2;
    text-align: center;
    white-space: nowrap;
    width: 100%;
    min-width: 0;
    flex-shrink: 0;
}

.row_item_label-end {
    margin-top: auto;
}

.row_item_value_wrapper {
    display: flex;
    flex-direction: column;
    gap: 2px;
    align-items: center;
    width: auto;
}

.row_item_value {
    font-size: 14px;
    color: #1e293b;
    line-height: 1.2;
    padding: 2px 4px;
    cursor: pointer;
    transition: all 0.2s;
    text-align: center;
    white-space: nowrap;
    border-radius: 2px;
    width: auto;
    box-sizing: border-box;
    min-width: 0;
    display: inline-block;
}

.row_item_value:hover {
    background: #f1f5f9;
}

.row_item_value.row_item_selected {
    background-color: #3b82f6;
    color: #fff;
    font-weight: 600;
}

.row_item_value span {
    font-size: 14px;
}

.relation-button-container {
    margin: 16px 0;
    padding: 0 16px;
}

.relation-button {
    width: 100%;
}

.divider {
    height: 1px;
    background: #e2e8f0;
    margin: 16px 0;
}
</style>

